package com.movies.service.controller.common;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;


@RestController
@RequestMapping("/file")
public class UploadController {

    @Value("${pictureFile.path}")
    private String picturePath;

    @Value("${pictureFile.path-mapping}")
    private String picturePathMapping;


//    通用文件上传（返回文件名）
    @PostMapping("/upload")
    @SaCheckLogin
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error(Constants.CODE_600, "文件为空");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf('.') + 1);
        }
        if (ext.isEmpty()) {
            ext = "dat"; // 默认扩展名
        }
        String random = UUID.randomUUID().toString().replace("-", "");
        String fileName = "upload." + random + "." + ext;
        try {
            Path staticDir = Paths.get(System.getProperty("user.dir"), "src", "main", "resources", "static");
            Files.createDirectories(staticDir);
            Path target = staticDir.resolve(fileName);
            try (InputStream in = file.getInputStream()) {
                Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
            }

            return Result.success("上传成功", fileName);
        } catch (IOException e) {
            return Result.error(Constants.CODE_600, "保存失败: " + e.getMessage());
        }
    }


//    富文本图片上传（返回完整 URL）
    @PostMapping("/rich-text-image")
    @SaCheckLogin
    public Result uploadRichTextImage(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.error(Constants.CODE_600, "文件为空");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf('.') + 1);
        }
        if (ext.isEmpty()) {
            ext = "png"; // 默认扩展名
        }
        String random = java.util.UUID.randomUUID().toString().replace("-", "");
        String fileName = "rich." + random + "." + ext;
        try {
            java.nio.file.Path dir = java.nio.file.Paths.get(picturePath);
            java.nio.file.Files.createDirectories(dir);
            java.nio.file.Path target = dir.resolve(fileName);
            try (java.io.InputStream in = file.getInputStream()) {
                java.nio.file.Files.copy(in, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }
            String baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
            String mapping = picturePathMapping.endsWith("/") ? picturePathMapping : (picturePathMapping + "/");
            String fullUrl = baseUrl + mapping + fileName;
            return Result.success("上传成功", fullUrl);
        } catch (java.io.IOException e) {
            return Result.error(Constants.CODE_600, "保存失败: " + e.getMessage());
        }
    }
}